# 进行UDP链接类
import socket
import struct 
import threading
from config.config import trigger_iface,trigger_multiip,trigger_multiport,master_ip,dport,server_ip
class udp_server(object):
    

    def __init__(self, my_ip, my_port):
        self.local_addr = (my_ip, my_port)
        self.socket = None

    def open(self):
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.socket.bind(self.local_addr)

    def close(self):
        if self.socket:
            self.socket.close()

    def sent_message(self, buf, d_ip, d_port):
        try:
            self.socket.sendto(bytes(buf), (d_ip, d_port))
        except Exception as e:
            print(f"Error1: {e}")
    def receive_message(self):
        receive_data = self.socket.recvfrom(1024)
        receive_content = receive_data[0]
        # receive_localAddr = receive_data[1]
        recv_buf = ""
        recv_message = []
        for i in range(len(receive_content)):
            recv_message.append(receive_content[i])
            recv_buf = recv_buf + str(hex(receive_content[i])) + " "
        return recv_message
    
lock = threading.Lock()

def join_multicast_group():
    # 创建UDP套接字
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    server_address = ("0.0.0.0", trigger_multiport)
    # 绑定套接字到本地地址和端口
    sock.bind(server_address)

    # 将套接字绑定到组播地址和端口
    group = socket.inet_aton(trigger_multiip)
    mreq = struct.pack('4sL', group, socket.INADDR_ANY)
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
    
    
    print(f"Listening on multi port {trigger_multiport}")
    return sock
def listen_unicast():

    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind(('0.0.0.0', dport))

    print(f"Listening on unicast port {dport}")
    return sock

# sock = listen_unicast()

# while True:
#     data, addr = sock.recvfrom(1024)
#     print(f"Received data multi from {addr}: {data.hex()}")
# def sniff_multicast_packets(multicast_ip, port, iface, stop_event,result_queue):
#     sock = join_multicast_group(multicast_ip, port, iface)
    
#     try:
#         sock.settimeout(3) 
#         sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
#         sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 255)
#         while not stop_event.is_set():
#             try:
#                 data, addr = sock.recvfrom(1024)
#                 print(f"Received data from {addr}: {data.hex()}")
#                 expected_header = b'\x4e\x5f\x14\x44\x08\x0f'
#                 if data[:6] == expected_header:
#                     # print("Trigger success!!!")
#                     with lock:  # 使用锁来确保线程安全
#                         result_queue.put(1)  # 成功后将state设置为1
#                     stop_event.set()  # 成功后停止监听
#                     return
#             except socket.timeout:
#                 continue  # 继续监听，直到超时或接收到正确的数据
#         with lock:
#             result_queue.put(0)  
#     finally:
#         sock.close()
#     return False
